package com.rico.ricorecognize.utils;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

    public static final String SDCARD_PATH="/mnt/sdcard/";

    public static void write(byte bytes[], File file){
        try {
            if(file.getParentFile()!=null&&!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static String getExtName(File file){
        String fileName=file.getName();
        return fileName.substring(fileName.lastIndexOf(".")+1);
    }

    public static List<File> listFiles(File file){
        List<File> fileList =new ArrayList<>();
        File[] files = file.listFiles();
        // 判断目录下是不是空的
        if(files==null) {
            return fileList;
        }
        for (File tempFile : files) {
            if(tempFile.isDirectory()){// 判断是否文件夹
                fileList.addAll(listFiles(tempFile));// 调用自身,查找子目录
            }else {
                fileList.add(tempFile);
            }
        }

        return fileList;
    }

    public static void checkPermission(Activity activity){
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(activity, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

        } else {
            Toast.makeText(activity, "授权成功！", Toast.LENGTH_SHORT).show();
        }
    }
}
